<?php
namespace common\services;
use Yii;
use AlibabaCloud\Sts\Sts;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Sts\V20150401\AssumeRole;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Client\Exception\ClientException;
/**
 * Class StsTest
 *
 * @package   AlibabaCloud\Tests\Feature
 */
class StsService
{    
  public $testFlag = 1;
    /**
     */
    //构建AssumeRole请求
    public function testSts()
    {
        //构建阿里云client时需要设置AccessKey ID和AccessKey Secret      
        AlibabaCloud::accessKeyClient('LTAI4G6DacVkPALwGTQYVV4X', '3kYYaVLveKPmd5dijFb0Dl1aAwLy1t')
            ->regionId('cn-shanghai')
            ->asDefaultClient();
        $result = Sts::v20150401()
           ->assumeRole()
           //指定角色ARN
           ->withRoleArn('acs:ram::1159161616955203:role/aliyunosstokengeneratorrole')
           //RoleSessionName即临时身份的会话名称，用于区分不同的临时身份
           ->withRoleSessionName('client_name')
           //设置权限策略以进一步限制角色的权限
           ->withPolicy('{
            "Statement": [
              {
                "Action": [
                  "oss:*"
                ],
                "Effect": "Allow",
                "Resource": ["acs:oss:*:*:*"]
              }
            ],
            "Version": "1"
          }')
           ->connectTimeout(60)
           ->timeout(65)
           ->request();
        return $result->toArray();
    }

    /**
     */
    //构建AssumeRole请求
    public function sts()
    {
      // var_dump(Yii::$app->params['sts_conf']);exit;
        //构建阿里云client时需要设置AccessKey ID和AccessKey Secret      
        AlibabaCloud::accessKeyClient(
          Yii::$app->params['sts_conf']['accessKeyId'], 
          Yii::$app->params['sts_conf']['accessKeySecret'])
            ->regionId(Yii::$app->params['sts_conf']['regionId'])
            ->asDefaultClient();
        $result = Sts::v20150401()
           ->assumeRole()
           //指定角色ARN
           ->withRoleArn(Yii::$app->params['sts_conf']['roleArn'])
           //RoleSessionName即临时身份的会话名称，用于区分不同的临时身份
           ->withRoleSessionName('client_name1')
           //设置权限策略以进一步限制角色的权限
           ->withPolicy('{
            "Statement": [
              {
                "Action": [
                  "oss:*"
                ],
                "Effect": "Allow",
                "Resource": ["acs:oss:*:*:*"]
              }
            ],
            "Version": "1"
          }')
           ->connectTimeout(60)
           ->timeout(65)
           ->request();
        return $result->toArray();
    }
}